/**
 * @description 路由拦截状态管理，目前两种模式：all模式与intelligence模式，其中partialRoutes是菜单暂未使用
 */
import Vue from 'vue'
import { asyncRoutes, constantRoutes, resetRouter } from '@/router'
import { getRouterList } from '@/api/router'
import { convertRouter, filterRoutes } from '@/utils/routes'
import { authentication, rolesControl } from '@/config'
import { isArray } from '@/utils/validate'
// 动态遍历路由
function forSearchArr(route, routerList) {
  const arrNew = []
  for (const item of route) {
    const itemNew = { ...item }
    if (
      itemNew.path === '/' ||
      itemNew.path === '*' ||
      itemNew.path === '/login' ||
      itemNew.path === '/register' ||
      itemNew.path === '/403' ||
      itemNew.path === '/404'
    ) {
      arrNew.push(itemNew)
      continue
    }
    for (const itemData of routerList) {
      if (itemData.url !== itemNew.name) {
        continue
      }
      if ([0, 1].indexOf(itemData.type) === -1) {
        // 非菜单路由
        continue
      }
      if (itemNew.children) {
        itemNew.children = forSearchArr(itemNew.children, routerList)
      }
      // if (itemData.icon) {
      //   itemNew.meta.icon = itemData.icon
      // }
      // if (itemData.name) {
      //   itemNew.meta.title = itemData.name
      // }
      arrNew.push(itemNew)
    }
  }
  return arrNew
}

const state = () => ({
  routes: [],
  resList: [], // 菜单管理权限
})
const getters = {
  routes: (state) => state.routes,
}
const mutations = {
  /**
   * @description 多模式设置路由
   * @param {*} state
   * @param {*} routes
   */
  setRoutes(state, routes) {
    state.routes = routes
  },
  setResList(state, list) {
    state.resList = list
  },
  /**
   * @description 修改Meta
   * @param {*} state
   * @param options
   */
  changeMenuMeta(state, options) {
    function handleRoutes(routes) {
      return routes.map((route) => {
        if (route.name === options.name) Object.assign(route.meta, options.meta)
        if (route.children && route.children.length)
          route.children = handleRoutes(route.children)
        return route
      })
    }
    state.routes = handleRoutes(state.routes)
  },
}
const actions = {
  setResList({ commit }, list) {
    commit('setResList', list)
  },
  /**
   * @description 多模式设置路由
   * @param {*} { commit }
   * @param mode
   * @returns
   */
  async setRoutes({ commit, state }, mode = 'none') {
    // 默认前端路由
    let routes = [...asyncRoutes]
    // 设置游客路由关闭路由拦截(不需要可以删除)
    const control = mode === 'visit' ? false : rolesControl
    // 设置后端路由(不需要可以删除)
    if (authentication === 'all') {
      const {
        data: { list },
      } = await getRouterList()
      if (!isArray(list))
        Vue.prototype.$baseMessage(
          '路由格式返回有误！',
          'error',
          'vab-hey-message-error'
        )
      if (list[list.length - 1].path !== '*')
        list.push({ path: '*', redirect: '/404', meta: { hidden: true } })
      routes = convertRouter(list)
    }
    // 根据权限和rolesControl过滤路由
    const accessRoutes = filterRoutes([...constantRoutes, ...routes], control)
    // 根据菜单过滤
    let finalRoutes = accessRoutes
    if (Array.isArray(state.resList) && state.resList.length > 0) {
      finalRoutes = forSearchArr(accessRoutes, state.resList)
    }
    // 设置菜单所需路由
    commit('setRoutes', JSON.parse(JSON.stringify(finalRoutes)))
    // 根据可访问路由重置Vue Router
    await resetRouter(accessRoutes)
  },
  /**
   * @description 修改Route Meta
   * @param {*} { commit }
   * @param options
   */
  changeMenuMeta({ commit }, options = {}) {
    commit('changeMenuMeta', options)
  },
}
export default { state, getters, mutations, actions }
